package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * leetcode 775. 全局倒置与局部倒置
 *
 * @author liw
 * @version 1.0
 * @date 2021/7/23 22:28
 */
public class IsIdealPermutation {

    public static void main(String[] args) {
        IsIdealPermutation test = new IsIdealPermutation();

        // true
//        int[] arr = {1, 0, 2};

        // false
        int[] arr = {1,2,0,3};

        boolean idealPermutation = test.isIdealPermutation(arr);
        System.out.println(idealPermutation);
    }

    public boolean isIdealPermutation(int[] nums) {
        int length = nums.length;
        if (length <= 2) {
            return true;
        }
        int min = nums[length - 1];
        for (int i = length - 3; i >= 0; i--) {
            if (nums[i] > min) {
                return false;
            }
            min = Math.min(min, nums[i + 1]);
        }
        return true;
    }

    public boolean isIdealPermutation2(int[] nums) {
        int length = nums.length - 1;
        if (length < 2) {
            return true;
        }
        for (int i = 0; i < length; i++) {
            if (i == nums[i]) {
                continue;
            }
            if (i == nums[i + 1] && i + 1 == nums[i]) {
                i++;
            } else {
                return false;
            }
        }
        return true;
    }

}
